package net.huashitong.ssydt.provider.wxpay.service;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.money.entity.SsMoneyOrder;
import net.huashitong.ssydt.provider.security.service.SsUserLoginTokenService;
import net.huashitong.ssydt.provider.wxpay.config.WeChatPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.16
 */
@Service
@Transactional
public class WeChatPayServiceImpl implements WeChatPayService {

    private Logger logger = LoggerFactory.getLogger(WeChatPayServiceImpl.class);

    private WeChatPayConfig weChatPayConfig;

    @Autowired
    public WeChatPayServiceImpl(WeChatPayConfig weChatPayConfig) {
        this.weChatPayConfig = weChatPayConfig;
    }

    @Autowired
    public SsUserLoginTokenService ssUserLoginTokenService;
    @Override
    public TreeMap<String, String> unifiedOrderForApp(SsMoneyOrder ssMoneyOrder, HttpServletRequest request) {
        int price = ssMoneyOrder.getOrderPrice()
                .multiply(new BigDecimal(100))
                .setScale(0, BigDecimal.ROUND_DOWN).intValue();
        WXPay wxpay = new WXPay(weChatPayConfig, WXPayConstants.SignType.MD5, weChatPayConfig.isUseSandbox());
        Map<String, String> data = new HashMap<>();
        data.put("body", String.format("%s - 华仕通教育", ssMoneyOrder.getOrderName()));
        data.put("out_trade_no", ssMoneyOrder.getOrderId());
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", String.valueOf(price));//订单总金额，单位为分
        data.put("spbill_create_ip", request.getRemoteAddr());
        data.put("notify_url", weChatPayConfig.getNotifyUrl());
        data.put("trade_type", "APP");  // 此处指定为APP支付

        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            TreeMap<String, String> outParams = new TreeMap<>();
            if (null != resp && resp.get("return_code").equals("SUCCESS")) {
                // 签名参数列表
                outParams.put("appid", weChatPayConfig.getAppID());
                outParams.put("partnerid", weChatPayConfig.getMchID());
                outParams.put("prepayid", resp.get("prepay_id"));
                outParams.put("package", "Sign=WXPay");
                outParams.put("noncestr", WXPayUtil.generateNonceStr());
                outParams.put("timestamp", this.getTimeStamp());
                String sign = WXPayUtil.generateSignature(outParams,weChatPayConfig.getKey());
                outParams.put("sign", sign);
                outParams.put("retcode", "0");
                outParams.put("retmsg", "OK");
                return outParams;
            }
            outParams.put("retcode", "-2");
            outParams.put("retmsg", "错误：获取prepayId失败");
            return outParams;
        } catch (Exception e) {
            logger.error("发起微信支付失败,message: [{}]", e.getMessage());
            throw new ServiceException("发起微信支付失败", e);
        }
    }
    /**
     * 生成随机字符
     * @return
     */
    private String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }


}
